package com.xsomnus.open.im.demo.netty.hi;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.Date;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/24 0024 14:24
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
public class FirstServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // (1) 在没有进行其他handler的处理, 默认的数据格式为 ByteBuf
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println(new Date() + ": 服务端读到的数据是 => " + byteBuf.toString(Charset.forName("UTF-8")));
        System.out.println(new Date() + ": 服务端写出数据 =====");
        ByteBuf out = getByteBuf(ctx);
        ctx.channel().writeAndFlush(out);

    }


    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        byte[] bytes = "你好!未来的路太漫长,走好每一步".getBytes(Charset.forName("UTF-8"));
        ByteBuf buf = ctx.alloc().buffer();
        buf.writeBytes(bytes);
        return buf;
    }


}
